package com.dkm.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.dkm.entity.Student;
import com.dkm.service.StudentService;
import com.dkm.util.PoiUtils;
import com.dkm.util.ResultUtil;

@RestController
@RequestMapping("/excel")
public class ExcelController {
	//注入业务层
	@Autowired
	private StudentService studentService;
	
	@RequestMapping("/exportExcel")
	public void exportExcel(HttpServletResponse response,String sids) {
		String downloadName = "dataInfo.xls";
		response.setCharacterEncoding("UTF-8");// 设置响应的字符编码格式
		response.setContentType("application/vnd.ms-excel");// 指明响应文件为excel类型
		ServletOutputStream out = null;
		try {
			// 文件名编码处理，防止浏览器下载文件名乱码
			response.setHeader("Content-disposition", "attachment;filename="
					+ new String(downloadName.getBytes("GB2312"), "ISO8859-1"));
			out = response.getOutputStream();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		//1、通过前端传来的数据生成Excel
		//2、通过前端传了来的id
		//获取成员集合
		List<Student> sList=studentService.batchFindBySid(sids);
		try {
			PoiUtils p = new PoiUtils();
			p.createExcel(sList, Student.class, out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@RequestMapping("/importExcel")
	public ResultUtil importExcel(@RequestParam("file") MultipartFile file) {
		
		String originalFilename = file.getOriginalFilename();// 得到上传文件的名称
		//把上传的Excel文件里的数据解析出来，调用方法，存入数据库
		PoiUtils poiUtils = new PoiUtils();// Excel工具类
		List<Student> list=null;//要新增的集合
		List<Student> slist=null;//新增后的集合
		try {
			list=(List<Student>) poiUtils.parseExcel(Student.class, file.getInputStream(), originalFilename);
			
			//执行批量保存
			slist=studentService.batchAddStudent(list);
		} catch (Exception e) {
			// TODO: handle exception
		}
		if(slist!=null) {
			return new ResultUtil(0, slist.size()+"条数据已导入",null);
		}
		return new ResultUtil(1, "导入失败",null);
	}
}
